/*
 * BtnCekNim.java
 *
 * Created on June 23, 2007, 7:50 AM
 *
 * To change this template, choose Tools | Template Manager
 * and open the template in the editor.
 */

package latihanibatis.ui.event;

import java.awt.Cursor;
import java.awt.event.ActionEvent;
import javax.swing.AbstractAction;
import javax.swing.JFormattedTextField;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import latihanibatis.dao.MahasiswaDao;
import latihanibatis.domain.Mahasiswa;
import latihanibatis.ui.PanelStatus;

/**
 *
 * @author javamaniac
 */
public class BtnCekNim extends AbstractAction {
    
    private final PanelStatus status;
    private final JFormattedTextField txtField;
    private final JFrame comp;
    private MahasiswaDao mhsDao;
    /**
     * Creates a new instance of BtnCekNim
     */
    public BtnCekNim(PanelStatus stat, JFormattedTextField txt, JFrame comp,
        MahasiswaDao mhsDao) {
        
        super();
        this.status = stat;
        this.txtField = txt;
        this.comp = comp;
        this.mhsDao = mhsDao;
    }
    
    public void actionPerformed(final ActionEvent evt) {
        comp.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
        final int intNim = ((Number)txtField.getValue()).intValue();
        
        if (intNim <= 0) {
            status.setStatus("Maap NIM Tidak Boleh Kurang Dari Sama Dengan NOL !!", "ERROR");
            showDialog("Maap NIM Tidak Boleh Kurang Dari \nSama Dengan NOL !!", "ERROR");
            comp.setCursor(Cursor.getDefaultCursor());
            
            txtField.selectAll();
        } else {
            final Mahasiswa mhsResult = mhsDao.selectMhsByNim(intNim);
            
            if (mhsResult == null) {
                status.setStatus("NIM " + intNim +" Mahasiswa Belum Terpakai !!", "BANTUAN");
                showDialog("NIM Mahasiswa : " + intNim + "\n Belum Terpakai !!", "BANTUAN");
            } else if (intNim == mhsResult.getNim()) {
                status.setStatus("NIM "+ intNim +" Mahasiswa Sudah Terpakai !!", "ERROR");
                showDialog("NIM Mahasiswa : "+ intNim +" \n Sudah Terpakai !!", "ERROR");
                txtField.selectAll();
            }
        }
        comp.setCursor(Cursor.getDefaultCursor());
    }
    
    private void showDialog(final String msg, final String type) {
        if (type.equals("ERROR")) {
            JOptionPane.showMessageDialog(null, msg, "Error !!!",
                JOptionPane.ERROR_MESSAGE);
        } else {
            JOptionPane.showMessageDialog(null, msg);
        }
    }
}
